<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :destroy-on-close="true"
      width="750px"
      draggable
      :align-center="true"
      @close="closeDialog"
      style="min-width: 750px"
    >
      <el-form
        v-show="!props.isReadonly"
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
        style="width: 100%"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="参数名称" prop="name" style="width: 96%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.name"
                  placeholder="请输入参数名称"
                  clearable
                />
                <span v-else>{{ formData.name }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="输入类型" prop="type" style="width: 96%">
                <el-select
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.type"
                  clearable
                  placeholder="请选择输入类型"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList('InputType')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{
                  dictionaryStore.filterDictName("InputType", formData.type)
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类型" prop="equipTypeId" style="width: 96%">
                <el-tree-select
                  v-model="formData.equipTypeId"
                  node-key="id"
                  :props="{
                    children: 'nodes',
                    label: 'assetTypeName',
                    disabled: '',
                  }"
                  placeholder="请选择类型"
                  check-strictly
                  :data="deviceList"
                  filterable
                  clearable
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="formData.type == 1">
              <el-form-item
                label="内容类型"
                prop="inputType"
                style="width: 96%"
              >
                <el-select
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.inputType"
                  clearable
                  placeholder="请选择内容类型"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'InputBoxType'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{
                  dictionaryStore.filterDictName(
                    "InputBoxType",
                    formData.inputType
                  )
                }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="formData.type == 1">
              <el-form-item
                label="长度限制"
                :prop="
                  formData.type == 1 && formData.inputType == '1'
                    ? 'inputLength'
                    : ''
                "
                style="width: 96%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.inputLength"
                  placeholder="请输入长度限制"
                  clearable
                />
                <span v-else>{{ formData.inputLength }}</span>
              </el-form-item>
            </el-col>
            <el-col
              :span="12"
              v-if="formData.type == 1 && formData.inputType == '2'"
            >
              <el-form-item
                label="小数点长度"
                :prop="
                  formData.type == 1 && formData.inputType == '2'
                    ? 'decimalPointLength'
                    : ''
                "
                style="width: 96%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.decimalPointLength"
                  placeholder="请输入小数点长度"
                  clearable
                />
                <span v-else>{{ formData.decimalPointLength }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort" style="width: 96%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.sort"
                  placeholder="请输入排序"
                  clearable
                />
                <span v-else>{{ formData.sort }}</span>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="8">
              <el-form-item
                label="是否必须输入"
                prop="mustEnter"
                style="width: 100%"
              >
                <el-radio-group
                  v-if="!props.isReadonly"
                  v-model="formData.mustEnter"
                >
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
                <span v-else>{{
                  dictionaryStore.filterDictName("Enabled", formData.mustEnter)
                }}</span>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="是否启用" prop="enabled" style="width: 96%">
                <el-radio-group
                  v-if="!props.isReadonly"
                  v-model="formData.enabled"
                >
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
                <span v-else>{{
                  dictionaryStore.filterDictName("Enabled", formData.enabled)
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks" style="width: 98%">
                <el-input
                  v-if="!props.isReadonly"
                  type="textarea"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  show-word-limit
                  :maxlength="250"
                  :autosize="{ minRows: 3, maxRows: 4 }"
                  clearable
                />

                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="formData.type > 1 && formData.type < 5"
        >
          <h4 class="mb-[20px] mt-[20px]">自定义数据</h4>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>

        <div class="formTable" v-if="formData.type > 1 && formData.type < 5">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column label="名称" props="lableName" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.lableName'"
                  :rules="rules.sonlableName"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.lableName"
                    placeholder="请输入名称"
                    clearable
                  />
                  <span v-else>{{ row.lableName }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="值" props="lableValue" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.lableValue'"
                  :rules="rules.sonlableValue"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.lableValue"
                    placeholder="请输入值"
                    clearable
                  />
                  <span v-else>{{ row.lableValue }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" props="remarks" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.remarks'"
                  :rules="rules.sonremarks"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.remarks"
                    placeholder="请输入备注"
                    clearable
                  />
                  <span v-else>{{ row.remarks }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top"
        title=""
        :column="2"
        size="large"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">参数名称</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.name || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">输入类型</div>
          </template>
          {{ dictionaryStore.filterDictName("InputType", formData.type) }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">类型</div>
          </template>
          {{ formData.assetTypeName || "" }}
        </el-descriptions-item>
        <el-descriptions-item v-if="formData.type == '1'">
          <template #label>
            <div class="cell-item">内容类型</div>
          </template>
          {{
            dictionaryStore.filterDictName("InputBoxType", formData.inputType)
          }}
        </el-descriptions-item>
        <el-descriptions-item v-if="formData.type == '1'">
          <template #label>
            <div class="cell-item">长度限制</div>
          </template>
          {{ formData.inputLength || "" }}
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.type == '1' && formData.inputType == '2'"
        >
          <template #label>
            <div class="cell-item">小数点长度</div>
          </template>
          {{ formData.decimalPointLength || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">排序</div>
          </template>
          {{ formData.sort || "" }}
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "暂无备注" }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { getAvailableListApi } from "@/utils/commonData";
defineOptions({
  name: "EAMEAMCUSTOMADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  name: "",
  type: "",
  assetKind: props.assetKind,
  equipTypeId: "",
  assetTypeName: "",
  assetTypeCode: "",
  mustEnter: "0",
  inputLength: "",
  inputType: "",
  decimalPointLength: "",
  sort: "",
  remarks: "",
  enabled: 1,
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  details: [
    {
      id: "",
      version: "",
      customId: "",
      lableName: "",
      lableValue: "",
      remarks: "",
      enabled: "",
      deleted: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "blur",
      pattern: "[^ \x20]+",
    },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择输入类型", trigger: "change" }],
  equipTypeId: [{ required: true, message: "请选择类型", trigger: "change" }],
  mustEnter: [],
  sort: [
    { required: true, message: "请输入排序", trigger: "blur" },
    // {
    //   required: true,
    //   pattern: "[^ \x20]+",
    //   message: "请输入排序",
    //   trigger: "blur",
    // },
    // { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  inputLength: [
    {
      required: true,
      message: "请输入正确的长度限制",
      trigger: "blur",
      validator: validateDegree,
    },
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
  ],
  inputType: [{ required: true, message: "请选择内容类型", trigger: "change" }],
  decimalPointLength: [
    {
      required: true,
      message: "请输入小数点长度",
      trigger: "blur",
      validator: validateDegree,
    },
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
  ],

  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
  sonlableName: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonlableValue: [
    { required: true, message: "请输入值", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonremarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});
function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入整数"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的整数"));
  } else {
    callback();
  }
}
const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  customId: "",
  lableName: "",
  lableValue: "",
  remarks: "",
  enabled: 1,
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    } else {
      formData.enabled = 1;
      formData.assetKind = props.assetKind;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.name = "";
  formData.type = "";
  formData.assetKind = props.assetKind;
  formData.equipTypeId = "";
  formData.assetTypeName = "";
  formData.assetTypeCode = "";
  formData.mustEnter = "0";
  formData.inputLength = "";
  formData.inputType = "";
  formData.decimalPointLength = "";
  formData.sort = "";
  formData.remarks = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 自定义字段保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/eam/eamcustom/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/eam/eamcustom/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

// 获取作业类型列表
const deviceList = ref(<any>[]);
async function getDeviceList() {
  const params = {
    assetKind: formData.assetKind,
  };
  deviceList.value = (await getAvailableListApi(params)) ?? [];
}
getDeviceList();
</script>

<style lang="scss" scoped>
.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-dialog .formTable .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable .el-table) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }

  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

:deep(
    .el-dialog .search-container .el-form-item--default .el-form-item__label
  ) {
  // 固定宽度
  justify-content: end;
}

:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 110px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
